<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { showToast } from 'vant';
import { useRouter } from 'vue-router';
import pay from '../assets/pay.jpg';
import { updateProductStockApi, getProductDetailApi } from '../api/products';

const router = useRouter();

// 订单信息
const orderInfo = ref({
  orderId: 'ORD' + Date.now().toString().slice(-8),
  amount: 299.00,
  createTime: new Date().toLocaleString()
});

// 支付二维码
const qrCodeUrl = ref(pay);

// 倒计时
const countdown = ref(15 * 60); // 15分钟，单位秒
let timer = null;

// 地址信息
const selectedAddress = ref(null);

// 开始倒计时
const startCountdown = () => {
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      showToast('支付超时，订单已取消');
      router.push('/cart');
    }
  }, 1000);
};

// 格式化倒计时显示
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
  const secs = (seconds % 60).toString().padStart(2, '0');
  return `${mins}:${secs}`;
};

// 模拟支付成功
const handlePaymentSuccess = async () => {
  if (!selectedAddress.value) {
    showToast('请选择收货地址');
    return;
  }

  clearInterval(timer);
  showToast('支付成功');

  // 获取购物车中的商品
  const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');

  // 正式减少商品库存
  const checkedItems = cartItems.filter(item => item.checked);
  try {
    // 并发更新所有商品的库存
    await Promise.all(checkedItems.map(async (item) => {
      // 获取商品的当前库存
      const productRes = await getProductDetailApi(item.id);
      if (productRes.success) {
        const currentStock = productRes.data.stock;
        // 计算新的库存（当前库存减去购买数量）
        const newStock = currentStock - item.num;
        // 更新库存
        return updateProductStockApi(item.id, newStock);
      }
    }));

    // 清空购物车中已支付的商品
    const uncheckedItems = cartItems.filter(item => !item.checked);
    localStorage.setItem('cartItems', JSON.stringify(uncheckedItems));

    // 跳转回首页
    router.push('/');
  } catch (error) {
    console.error('支付处理失败:', error);
    showToast('支付处理异常，请联系客服');
  }
};

// 取消支付 - 修改为返回购物车页面
const cancelPayment = () => {
  clearInterval(timer);
  // 取消支付时返回购物车页面
  router.push('/cart');
};

// 跳转到地址管理页面
const goToAddressManagement = () => {
  router.push('/settings');
};

// 获取默认地址
const getDefaultAddress = () => {
  const addresses = JSON.parse(localStorage.getItem('addresses') || '[]');
  if (addresses.length > 0) {
    // 优先选择默认地址
    const defaultAddress = addresses.find(addr => addr.isDefault);
    selectedAddress.value = defaultAddress || addresses[0];
  }
};

// 刷新地址信息（从地址管理页面返回时调用）
const refreshAddress = () => {
  getDefaultAddress();
};

onMounted(() => {
  startCountdown();
  getDefaultAddress();

  // 从购物车获取实际的订单金额
  const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
  if (cartItems.length > 0) {
    const totalAmount = cartItems
      .filter(item => item.checked)
      .reduce((sum, item) => {
        const price = typeof item.price === 'string' ? parseFloat(item.price) : item.price;
        return sum + price * item.num;
      }, 0);

    if (totalAmount > 0) {
      orderInfo.value.amount = totalAmount;
    }
  }
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>

<template>
  <div class="payment-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="订单支付"
      left-text="返回"
      left-arrow
      @click-left="cancelPayment"
    />

    <!-- 地址选择 -->
    <div class="address-section" v-if="selectedAddress">
      <van-cell-group>
        <van-cell title="收货地址" is-link @click="goToAddressManagement">
          <template #title>
            <div class="address-info">
              <div class="address-header">
                <span class="name">{{ selectedAddress.name }}</span>
                <span class="phone">{{ selectedAddress.phone }}</span>
                <van-tag v-if="selectedAddress.isDefault" type="danger" size="mini">默认</van-tag>
              </div>
              <div class="address-detail">
                {{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detail }}
              </div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <div class="address-section" v-else>
      <van-cell-group>
        <van-cell title="收货地址" is-link @click="goToAddressManagement">
          <template #value>
            <span class="no-address">请选择收货地址</span>
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 订单信息 -->
    <div class="order-info">
      <div class="order-id">订单编号: {{ orderInfo.orderId }}</div>
      <div class="order-time">创建时间: {{ orderInfo.createTime }}</div>
      <div class="order-amount">支付金额: <span>¥{{ orderInfo.amount.toFixed(2) }}</span></div>
    </div>

    <!-- 支付二维码区域 -->
    <div class="qr-code-section">
      <div class="countdown">支付剩余时间: {{ formatTime(countdown) }}</div>
      <div class="qr-code-container">
        <van-image
          width="200"
          height="200"
          fit="contain"
          :src="qrCodeUrl"
        />
      </div>
      <div class="payment-tip">
        <p>请使用微信/支付宝扫描二维码完成支付</p>
        <p>请在15分钟内完成支付，超时订单将自动取消</p>
      </div>
    </div>

    <!-- 支付结果 -->
    <div class="payment-actions">
      <van-button
        type="primary"
        block
        @click="handlePaymentSuccess"
        class="success-btn"
      >
        已完成支付
      </van-button>
      <van-button
        plain
        block
        @click="cancelPayment"
        class="cancel-btn"
      >
        取消支付
      </van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.payment-page {
  padding-bottom: 60px;
  background-color: #f7f8fa;
  min-height: 100vh;

  .address-section {
    margin-bottom: 10px;
    background-color: #fff;

    .address-info {
      .address-header {
        display: flex;
        align-items: center;
        margin-bottom: 4px;

        .name {
          font-size: 16px;
          font-weight: bold;
          margin-right: 12px;
        }

        .phone {
          font-size: 14px;
          color: #666;
          flex: 1;
        }
      }

      .address-detail {
        font-size: 14px;
        color: #333;
        line-height: 1.4;
      }
    }

    .no-address {
      color: #999;
    }
  }

  .order-info {
    background-color: #fff;
    padding: 15px;
    margin-bottom: 10px;
    font-size: 14px;
    color: #666;

    .order-id {
      margin-bottom: 8px;
    }

    .order-time {
      margin-bottom: 8px;
    }

    .order-amount {
      font-size: 16px;

      span {
        color: #f44;
        font-weight: bold;
      }
    }
  }

  .qr-code-section {
    background-color: #fff;
    padding: 20px 15px;
    margin-bottom: 10px;
    text-align: center;

    .countdown {
      color: #f44;
      font-size: 15px;
      margin-bottom: 15px;
    }

    .qr-code-container {
      margin: 0 auto 15px;
      width: 200px;
      height: 200px;
      border: 1px solid #eee;
      padding: 10px;
    }

    .payment-tip {
      color: #999;
      font-size: 13px;
      line-height: 1.6;
    }
  }

  .payment-actions {
    padding: 0 15px;

    .success-btn {
      margin-bottom: 10px;
    }

    .cancel-btn {
      border-color: #ccc;
      color: #666;
    }
  }
}

// 暗色主题样式
[data-theme="dark"] {
  .payment-page {
    background-color: #1a1a1a;

    .address-section,
    .order-info,
    .qr-code-section {
      background-color: #2c2c2c;
      color: #e0e0e0;
    }

    .address-section {
      .address-info {
        .address-header {
          .name {
            color: #ffffff;
          }

          .phone {
            color: #bbbbbb;
          }
        }

        .address-detail {
          color: #e0e0e0;
        }
      }

      .no-address {
        color: #999999;
      }
    }

    .order-info {
      color: #cccccc;

      .order-id,
      .order-time {
        color: #bbbbbb;
      }

      .order-amount {
        span {
          color: #ff6b6b;
        }
      }
    }

    .qr-code-section {
      .countdown {
        color: #ff6b6b;
      }

      .qr-code-container {
        border: 1px solid #444444;
      }

      .payment-tip {
        color: #aaaaaa;
      }
    }

    .payment-actions {
      .cancel-btn {
        border-color: #666666;
        color: #cccccc;
      }
    }
  }
}
</style>